package com.trm.user.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.trm.role.dao.RoleDao;
import com.trm.student.dao.StudentDao;
import com.trm.user.dao.UserDao;

public class UserServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String methodName = request.getParameter("action");
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this.getClass().newInstance(), request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户列表
     * 
     * @param request
     * @param response
     */
    public void userList(HttpServletRequest request, HttpServletResponse response) {
        String page = request.getParameter("page"); // 页码
        UserDao userDao = new UserDao();
        if (page != null && !"".equals(page)) {
            userDao.setPage(Integer.valueOf(page));
        }
        List<Map<String, Object>> list = userDao.getUserList();
        // 获得用户数量
        int count = userDao.getUserCountByRoleId(null);
        // 页数量
        int pageNumber = count / userDao.getPageSize();
        if (count % userDao.getPageSize() > 0) {
            pageNumber++;
        }
        if (pageNumber == 0) {
            pageNumber = 1;
        }
        request.setAttribute("list", list);
        request.setAttribute("page", userDao.getPage());
        request.setAttribute("pageNumber", pageNumber);
        try {
            request.getRequestDispatcher("/manager/userManager.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑页面
     * 
     * @param request
     * @param response
     */
    public void add(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String roleId = null;
        if (id != null && !"".equals(id)) {
            UserDao userDao = new UserDao();
            Map<String, Object> user = userDao.getUserById(id);
            request.setAttribute("user1", user);
            roleId = user.get("role").toString();
        }
        RoleDao roleDao = new RoleDao();
        List<Map<String, Object>> roleList = roleDao.getRoleList();
        for (Map<String, Object> role : roleList) {
            if (roleId != null && roleId.equals(role.get("id").toString())) {
                role.put("selected", "selected");
            }
        }
        request.setAttribute("roleList", roleList);
        try {
            request.getRequestDispatcher("/manager/addUser.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存用户
     * 
     * @param request
     * @param response
     */
    public void saveUser(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String role = request.getParameter("role");
        // 封装参数到map
        Map<String, String> params = new HashMap<String, String>();
        params.put("role", role);
        params.put("account", account);
        params.put("password", password);
        params.put("name", name);
        params.put("sex", sex);
        UserDao userDao = new UserDao();
        if (id == null || "".equals(id)) {
            int result = userDao.addUser(params);
        } else {
            params.put("id", id);
            int result = userDao.updateUserById(params);
        }
        try {
            response.sendRedirect("UserServlet?action=userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除用户
     * 
     * @param request
     * @param response
     */
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        StudentDao sDao = new StudentDao();
        int result = sDao.deleteUserById(id);
        try {
            response.sendRedirect("UserServlet?action=userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改密码
     * 
     * @param request
     * @param response
     */
    public void modifyPassword(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getRequestDispatcher("/personal/editPassword.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改密码
     * 
     * @param request
     * @param response
     */
    public void updatePassword(HttpServletRequest request, HttpServletResponse response) {
        String password = request.getParameter("password");
        String userId = request.getParameter("id");
        String oldPassword = request.getParameter("oldPassword");
        String result = "";
        UserDao userDao = new UserDao();
        if (userDao.selectPassword(userId, oldPassword) > 0) {
            userDao.updatePassword(userId, password);
            result = "修改密码成功！";
        } else {
            result = "初始密码输入不正确！";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
        return;
    }

    /**
     * 查询账号
     * 
     * @param request
     * @param response
     */
    public void selectAccount(HttpServletRequest request, HttpServletResponse response) {
        String account = request.getParameter("account");
        String userId = request.getParameter("id");
        String result = "";
        UserDao userDao = new UserDao();
        if (userDao.selectAccount(userId, account) > 0) {
            result = "该账号在系统中已存在，请重新设置！";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
        return;
    }
}
